<template>
  <div ref="barChart" class="chart"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'BarChart',
  props: {
    chartData: {
      type: Object,
      required: true,
    },
  },
  mounted() {
    this.drawBarChart();
  },
  methods: {
    drawBarChart() {
      // 基于准备好的dom，初始化echarts实例
      const chart = echarts.init(this.$refs.barChart);

      // 指定图表的配置项和数据
      const option = {
        xAxis: {
          type: 'category',
          data: this.chartData.labels,
        },
        yAxis: {
          type: 'value',
        },
        series: [{
          data: this.chartData.datasets[0].data,
          type: 'bar',
          barWidth: '60%', // 可调整柱状图宽度
        }],
      };

      // 使用刚指定的配置项和数据显示图表。
      chart.setOption(option);
    },
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.drawBarChart();
      },
    },
  },
};
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
